import React, { Component } from 'react'
import { DatePicker, Select, message, Cascader, Input, Button, Tooltip } from 'antd'
import WrapperHeader from './wrapper_header'
import ProductStyle from '../../product/product.module.sass'
import locale from 'antd/es/date-picker/locale/zh_CN'
import RiskTable from '../common_table/risk_table'
import SceneStyle from '../../../style/scene/scene.module.sass'
import SceneTable from '../common_table/scene_table'
import SceneTableBond from '../common_table/scene_table_bond'
import SceneTableFuture from '../common_table/scene_table_future'
import SceneBasis from '../common_table/scene_basis'
import SceneHeaders from './scene_common_header'
import { _sceneSocketMarket, _sceneMarketVar, _sceneMarketNeutral, _sceneBondMarket, _sceneFuture } from '../../../apis/index'
import url from 'url'
import cookie from 'js-cookie'
import CommonCharts from '../charts/common_charts'
import { linesOptions, radarOption, barsOptions, chartsColors, areasOptions } from '../../../Utils/charts_config/charts_config'
import { axios } from '../../../Utils/index'
import moment from 'moment'

const { Option } = Select
const options = [
    {
        value: '到期收益率',
        label: '到期收益率',
        children: [
            {
                value: 'n_long_yield',
                label: '长债收益率'
            },
            {
                value: 'n_base_rate',
                label: '货币市场基准利率'
            },
            {
                value: 'n_base_rate_volatility',
                label: '货币市场基准利率波动'
            },
            {
                value: 'n_term_spread',
                label: '期限利差'
            },
            {
                value: 'n_long_credit_spread',
                label: '长期信用利差'
            }
        ]
    },
    {
        value: '宏观经济',
        label: '宏观经济',
        children: [
            {
                value: 'n_IVA_yoy',
                label: '工业增加值当月同比'
            },
            {
                value: 'n_PMI',
                label: 'PMI'
            }
        ]
    },
    {
        value: '通货膨胀',
        label: '通货膨胀',
        children: [
            {
                value: 'n_CPI_yoy',
                label: 'CPI当月同比'
            },
            {
                value: 'n_PMI_yoy',
                label: 'PPI当月同比'
            }
        ]
    },
    {
        value: '货币供应',
        label: '货币供应',
        children: [
            {
                value: 'n_M2_yoy',
                label: 'M2同比'
            },
            {
                value: 'n_M1_M2_diff',
                label: 'M1-M2增速差'
            }
        ]
    },
    {
        value: '实体融资需求',
        label: '实体融资需求',
        children: [
            {
                value: 'n_social_finance_yoy',
                label: '社融存量同比'
            }
        ]
    }
]

const futureOptions = [
    {
        value: '商品期货',
        label: '商品期货',
        children: [
            {
                value: 'n_nhci_volatility',
                label: '南华商品指数'
            },
            {
                value: 'n_nhii_volatility',
                label: '南华工业品指数'
            },
            {
                value: 'n_nhai_volatility',
                label: '南华农产品指数'
            },
            {
                value: 'n_nhmi_volatility',
                label: '南华金属指数'
            },
            {
                value: 'n_nheci_volatility',
                label: '南华能化指数'
            },
            {
                value: 'n_nhnmi_volatility',
                label: '南华有色金属指数'
            },
            {
                value: 'n_nhbmi_volatility',
                label: '南华黑色指数'
            },
            {
                value: 'n_nhpmi_volatility',
                label: '南华贵金属指数'
            }
        ]
    },
    {
        value: '股指期货',
        label: '股指期货',
        children: [
            
            {
                value: 'n_ic_volatility',
                label: '中证500股指期货'
            },
            {
                value: 'n_ih_volatility',
                label: '上证50股指期货'
            },
            {
                value: 'n_if_volatility',
                label: '沪深300股指期货'
            }
        ]
    }
]

const neutralOptions = [
    {
        value: 'n_basis_cost',
        label: '年化基差成本'
    },
    {
        value: '股指涨跌幅',
        label: '股指涨跌幅',
        children: [
            {
                value: 'n_sse50_change',
                label: '上证50涨跌幅'
            },
            {
                value: 'n_hs300_change',
                label: '沪深300涨跌幅'
            },
            {
                value: 'n_csi500_change',
                label: '中证500涨跌幅'
            },
            {
                value: 'n_csi800_change',
                label: '中证800涨跌幅'
            },
            {
                value: 'n_sse_change',
                label: '上证指数涨跌幅'
            },
            {
                value: 'n_gem_change',
                label: '创业板指数涨跌幅'
            }
        ]
    },
    {
        value: 'n_ls_diff',
        label: '大小市值涨跌幅之差'
    },
    {
        value: 'n_sse_volatility',
        label: '上证指数波动率'
    },
    {
        value: 'n_sse_liquidity',
        label: '上证指数流动性'
    },
]

const dimensionDesc = [
    {
        n_long_yield: {name: '长债收益率', status: '上行'},
        n_base_rate: {name: '货币市场基准利率', status: '上行'},
        n_IVA_yoy: {name: '工业增加值当月同比', status: '上行'},
        n_PMI: {name: 'PMI', status: '上行'},
        n_CPI_yoy: {name: 'CPI当月同比', status: '上行'},
        n_PMI_yoy: {name: 'PPI当月同比', status: '上行'},
        n_M2_yoy: {name: 'M2同比', status: '上行'},
        n_M1_M2_diff: {name: 'M1-M2增速差', status: '上行'},
        n_social_finance_yoy: {name: '社融存量同比', status: '上行'},
        n_base_rate_volatility: {name: '货币市场基准利率波动', status: '扩大'},
        n_term_spread: {name: '期限利差', status: '扩大'},
        n_long_credit_spread: {name: '长期信用利差', status: '扩大'},
    },
    {
        n_long_yield: {name: '长债收益率', status: '下行'},
        n_base_rate: {name: '货币市场基准利率', status: '下行'},
        n_IVA_yoy: {name: '工业增加值当月同比', status: '下行'},
        n_PMI: {name: 'PMI', status: '下行'},
        n_CPI_yoy: {name: 'CPI当月同比', status: '下行'},
        n_PMI_yoy: {name: 'PPI当月同比', status: '下行'},
        n_M2_yoy: {name: 'M2同比', status: '下行'},
        n_M1_M2_diff: {name: 'M1-M2增速差', status: '下行'},
        n_social_finance_yoy: {name: '社融存量同比', status: '下行'},
        n_base_rate_volatility: {name: '货币市场基准利率波动', status: '收窄'},
        n_term_spread: {name: '期限利差', status: '收窄'},
        n_long_credit_spread: {name: '长期信用利差', status: '收窄'},
    }
]

const { query } = url.parse(window.location.href, true)

const nowData = moment(new Date()).format('YYYY-MM-DD')
const startDate = moment(new Date().getTime() - (365 * 24 * 60 * 60 * 1000)).format('YYYY-MM-DD')

export default class Scene extends Component {
    constructor(props) {
        super(props)
        this.state = {
            dimension: 'n_long_yield',
            dimensionLatest: 'n_term_spread',
            neutralType: 'n_basis_cost',
            productName: '',
            indexName: 'c_hs300_trend',
            navType: 'n_swanav',
            scoketLevel: '0.90',
            bondLevel: '0.90',
            futureLevel: '0.90',
            startDate: startDate,
            endDate: nowData,
            socketDate: `${startDate}:${nowData}`,
            bondDate: `${startDate}:${nowData}`,
            neutralDate: `${startDate}:${nowData}`,
            neutraStart: startDate,
            neutralEnd: nowData,
            randarDate: `${startDate}:${nowData}`,
            randarStart: startDate,
            randarEnd: nowData,
            futureDay: 'scenario_future_30',
            futureDev: 'n_nhci_volatility',
            futureDate: `${startDate}:${nowData}`,
            futureEnd: nowData,
            futureStart: startDate,
            filterDimension: options,
            filterState: true,
            dimensionOptions: options,
            lastDimensionOptions: options,
            socketSharpe: '0.025',
            futureSharpe: '0.025',
            bondsSharpe: '0.025',
            nQuantile: '0.2'
        }
    }
    async _getRiskRate () {
        const { query } = url.parse(window.location.href, true)
        
        this.setState({productName: query.name})
        const data = await axios({
            url: '/api/hszcpz/product/getRiskIndicator',
            method: 'POST',
            data: JSON.stringify({
                fundId: query.id,
                token: cookie.get('token'),
                interval: 'year',
                benchMarkId: '',
                corId: ''
            })
        })

            message.destroy()
            if (!data.hasOwnProperty('status')) {
                message.info('接口获取数据失败')
                return
            }

            this.setState({loading: false})
            if (data.status !== 'success') {
                message.info(data.errorReason)
                return
            }
            if (!data.hasOwnProperty('result')) {
                message.info('接口获取数据失败')
                return
            }

            let result = JSON.parse(data.result)
            if (result.status === 'success') {
                return result.result
            } else {
                message.error('获取数据失败')
            }
    }

    // 股票多头--标域图
    async _socketMarket (param) {
        const { query } = url.parse(window.location.href, true)
        const params = param || {
            token: cookie.get('token'),
            fundId: query.id,
            indexName: this.state.indexName,
            navType: this.state.navType,
            confLevel: this.state.scoketLevel,
            dateRange: this.state.socketDate,
            Rfann: this.state.socketSharpe
        }
        this.setState({socketDesc: false})
        const data = await _sceneSocketMarket(params)
        if (data.status === 'success') {
            const result = JSON.parse(data.result)

            if (result.status === 'success') {
                this.setState({socketDesc: true})
                return result.result
            } else {
                message.error(result.result || result.errorReason)
                return
            }
        } else {
            message.error('获取数据失败')
            return
        }
    }

    // 市场变量--radar
    async _getMarketVar (param) {
        const { query } = url.parse(window.location.href, true)
        const params = param || {
            token: cookie.get('token'),
            fundId: query.id,
            navType: this.state.navType,
            dateRange: this.state.randarDate
        }

        const data = await _sceneMarketVar(params)
        if (data.status === 'success') {
            const result = JSON.parse(data.result)
            if (result.status === 'success') {
                return result.result
            } else {
                message.error(result.result || result.errorReason)
                return
            }
        } else {
            message.error('获取数据失败')
            return
        }
    }

    // 股票多投 -- 市场分阶段表现获取数据
    async _getMarketNeutral (param) {
        const params = param || {
            token: cookie.get('token'),
            fundId: query.id,
            navType: this.state.navType,
            dateRange: this.state.neutralDate,
            dimension: this.state.neutralType
        }

        const data = await _sceneMarketNeutral(params)
        if (data.status === 'success') {
            const result = JSON.parse(data.result)
            if (result.status === 'success') {
                return result.result
            } else {
                message.error(result.result || result.errorReason)
                return
            }
        } else {
            message.error('获取数据失败')
            return
        }
    }

    // 获取债券数据
    async _getBondMarket (param) {
        const { query } = url.parse(window.location.href, true)
        const params = param || {
            token: cookie.get('token'),
            fundId: query.id,
            navType: this.state.navType,
            dateRange: this.state.bondDate,
            dimension1: this.state.dimension,
            dimension2: this.state.dimensionLatest,
            confLevel: this.state.bondLevel,
            Rfann: this.state.bondsSharpe
        }
        this.setState({bondDesc: false})
        const data = await _sceneBondMarket(params)
        if (data.status === 'success') {
            const result = JSON.parse(data.result)
            if (result.status === 'success') {
                this.setState({bondDesc: true})
                return result.result
            } else {
                message.error(result.result || '获取数据失败')
                return
            }
        } else {
            message.error('获取数据失败')
            return
        }
    }

    // 获取期货数据
    async _getFuture (param) {
        const { query } = url.parse(window.location.href, true)
        const params = param || {
            token: cookie.get('token'),
            dateRange: this.state.futureDate,
            fundId: query.id,
            futureDev: this.state.futureDev,
            nQuantile: this.state.nQuantile,
            futureDay: this.state.futureDay,
            navType: this.state.navType,
            confLevel: this.state.futureLevel,
            Rfann: this.state.futureSharpe
        }
        this.setState({futureDesc: false})
        const data = await _sceneFuture(params)  
        if (data.status === 'success') {
            const result = JSON.parse(data.result)
            if (result.status === 'success') {
                this.setState({futureDesc: true})
                return result.result
            } else {
                message.error(result.result || result.errorReason)
                return
            }
        } else {
            message.error('获取数据失败')
            return
        }
    }

    // 绘制标域图和表格
    async _chartSocket (params) {
        const data = await this._socketMarket(params)
        const navType = {n_swanav: '复权累计净值', n_added_nav: '累计净值', n_nav: '单位净值'}
        let lineOption = JSON.parse(JSON.stringify(linesOptions))
        let optionSeries = []
        let areaMarket = []
        let markColor = []
        lineOption.yAxis[0].name = navType[this.state.navType]
        lineOption.legend.data = [query.name] 
        lineOption.grid.bottom = '16%'
        lineOption.grid.top = '46px'
        lineOption.dataZoom[0].bottom = '28px'
        lineOption.yAxis[0].axisTick = { show: false }
        lineOption.yAxis[0].splitLine = {
            lineStyle: {
                type: 'dashed',
                color: "#ddd",
            }

        }
        // console.log(data)
        if (data) {
            data['figure']['scenario_data'].forEach((item, index) => {
                areaMarket.push(Object.keys(item).toString())
            })

            if (data.table) {
                this.refs.socketTable._initData(data.table)
            }

            areaMarket.forEach((item, index) => {
                let colorItem = ''
                
                if (data['figure']['scenario_data'][index][item] === 'blue') {
                    colorItem = 'rgba(183, 227, 255, 0.4)'
                } else if (data['figure']['scenario_data'][index][item] === 'red') {
                    colorItem = 'rgba(255, 201, 201, 0.4)'
                } else if (data['figure']['scenario_data'][index][item] === 'green') {
                    // colorItem =  'rgba(188, 255, 183, 0.4)'
                    colorItem = 'rgba(255, 237, 183, 0.4)'
                } else {
                    colorItem = 'rgba(255, 237, 183, 0.4)'
                }
                if (index === 0) {
                    markColor.push([{}, {
                        xAxis: item.split('|')[1],
                        itemStyle: {color: colorItem}
                    }])
                } else if (index === areaMarket.length -1) {
                    markColor.push([{
                        xAxis: item.split('|')[0],
                        itemStyle: {color: colorItem}
                    }, {}])
                } else {
                    markColor.push([{
                        xAxis: item.split('|')[0],
                        itemStyle: {color: colorItem}
                    }, {
                        xAxis: item.split('|')[1]
                    }])
                }
                
            })
            console.log(data)
            lineOption.xAxis[0].data = data.figure.x_axis
            optionSeries = [{
                name: query.name,
                type: 'line',
                smooth: true,
                symbol: 'none',
                markArea: {
                    data: markColor
                },
                data: data.figure.fund_data
            }]
            
        }
        lineOption.series = optionSeries
        this.refs.socketMarket.setOpitions(lineOption)
    }

    // 绘制radar图表
    async _marketVarChart () {
        const data = await this._getMarketVar()
        let radarOptions = Object.assign({}, radarOption)
        let chartDate = this.state.randarDate.split(':')
        // console.log(chartDate)
        let series = []
        radarOptions.radar.startAngle = 90
        radarOptions.radar.scale = true
        radarOptions.radar.indicator = [
            {name: '常数项'},
            {name: '上证50涨跌幅'},
            {name: '中证500涨跌幅'},
            {name: '大小市值涨跌幅之差'},
            {name: '上证指数收益率波动率（周度波动率）'},
            {name: '上证指数流动性（平均成交量）'},
        ]

        if (data) {
            series.push({
                type: 'radar',
                itemStyle: {
                    color:'rgba(61, 165, 216, .9)'
                },
                startAngle: 95,
                symbolSize: 10,
                lineStyle: {normal: { color: 'rgba(61, 165, 216, 1)'}},
                areaStyle: {color: 'rgba(0, 255, 100, 0.1)', normal: {color: 'rgba(61, 165, 216, .3)'}},
                data: [{
                    value: data
                }]
            })

            radarOptions.series = series
        }

        radarOptions.tooltip.formatter = (value, ticket) => {
        let itemDesc = `${chartDate[0]}——${chartDate[1]}<br />`
            value.value.forEach((item, i) => {
                itemDesc += `${value.marker}${radarOptions.radar.indicator[i].name}：${parseFloat(item).toFixed(2)}<br />`
            })
            return itemDesc
        }
        this.refs.socketMarketVar.setOpitions(radarOptions)
    }

    // 股票市场表现绘制图表
    async _neutralChart (params) {
        const { neutralType } = this.state
        const data = await this._getMarketNeutral(params)
        let neutralDate = this.state.neutralDate.split(':')
        let rateData = null
        let lineData = null
        let series = []
        let neutralOptions = JSON.parse(JSON.stringify(barsOptions))
        
        if (data) {
            let tableJson = JSON.parse(JSON.stringify(data))
            this.refs.neutralTable._initData(tableJson, neutralType)
            neutralOptions.legend = {
                x: 'center',
                bottom: '0',
                textStyle: {
                    color: '#90979c',
                },
                data: ['年化周收益率', '胜率']
            }
            neutralOptions.yAxis[0].axisTick = {show: false}
            neutralOptions.yAxis[0].splitLine = {
                lineStyle: {
                    type: 'dashed',
                    color: '#ccc'
                }
            }

            neutralOptions.tooltip.formatter = (value) => {
            let itemDesc = `${neutralDate[0]}——${neutralDate[1]}<br />`
                value.forEach((item, index) => {
                    if (index < value.length -1) {
                        itemDesc += `${item.marker}${item.seriesName}：${parseFloat(item.value).toFixed(2)}%<br />`
                    } else {
                        itemDesc += `${item.marker}${item.seriesName}：${parseFloat(item.value).toFixed(2)}<br />`
                    }
                })

                return itemDesc
            }
            neutralOptions.title = {}
            neutralOptions.yAxis[0].name = ''
            neutralOptions.yAxis.push({
                
                min: 0,
                max: 1,
                splitNumber: 1 / 4,
                nameLocation: 'end',
                axisTick: {show: false},
                nameTextStyle: {
                    color: '#999',
                    align: 'left'
                },
                color: '#ccc',
                axisLabel: {
                    show: false,
                    typeStyle: {
                        color: '#333'
                    },
                    color: '#999'
                },
                axisLine: {
                    show: false,
                    lineStyle: {
                        color: '#666'
                    }
                },
                splitLine: {
                    lineStyle: {
                        type: 'dashed',
                        color: '#ccc'
                    }
                }
            })

            rateData = data.n_return_a
            lineData = data.w_rate
            
            if (rateData && lineData) {
                let keys = Object.keys(rateData)
                
                if (keys.length > 3) {
                    const sortKey = []
                    keys.forEach((item, index) => {
                        switch (item) {
                            case '<5':
                                sortKey[0] = item
                                break
                            case '5-10':
                                sortKey[1] = item
                                break
                            case '10-15':
                                sortKey[2] = item
                                break
                            case '15-20':
                                sortKey[3] = item
                                break
                            case '>20':
                                sortKey[4] = item
                                break
                            default:
                                break
                        }
                    })
                    keys = sortKey
                    neutralOptions.xAxis= [{data: keys}]
                } else {
                    const midKey = []
                    keys.forEach((item, index) => {
                        switch (item) {
                            case '高':
                                midKey[0] = '极大值'
                                break
                            case '中':
                                midKey[1] = '正常'
                                break
                            case '低':
                                midKey[2] = '极小值'
                                break
                            default:
                                break
                        }
                    })
                    
                    neutralOptions.xAxis= [{data: midKey}]
                }
                
                neutralOptions.xAxis[0].offset = 0
                neutralOptions.xAxis[0].axisLine = {
                    onZero: false,
                    show: true,
                    lineStyle: {
                        color: '#ccc'
                    }
                }

                neutralOptions.xAxis[0].axisLabel = {
                    margin: 10,
                    color: '#999',
                    show: true
                }

                neutralOptions.xAxis[0].axisTick = {
                    show: true,
                    position: 'bottom',
                    inside: false
                }
                let rateList = [], barList = []
                keys.forEach((item, index) => {
                    rateList.push(rateData[item])
                    barList.push(lineData[item])
                })

                series.push({
                    name: '年化周收益率',
                    type: 'line',
                    smooth: true,
                    symbol: 'none',
                    data: rateList
                })

                series.push({
                    name: '胜率',
                    type: 'bar',
                    barWidth: 30,
                    yAxisIndex: 1, 
                    smooth: true,
                    data: barList,
                    itemStyle: {
                        normal: { barBorderRadius: 5, color: chartsColors[4]}
                    }
                })

            }
        }
        neutralOptions.series = series
        this.refs.neutralChart.setOpitions(neutralOptions)
    }

    // 债券市场表现标域和图表
    async _bondMarket () {
        const data = await this._getBondMarket()
        const navType = {n_swanav: '复权累计净值', n_added_nav: '累计净值', n_nav: '单位净值'}
        let bondOption = JSON.parse(JSON.stringify(linesOptions))
        let optionSeries = []
        let areaMarket = []
        let markColor = []
        bondOption.yAxis[0].axisTick = { show: false }
        bondOption.yAxis[0].name = navType[this.state.navType]
        bondOption.legend.data = [query.name] 
        bondOption.grid.bottom = '16%'
        bondOption.grid.top = '46px'
        bondOption.dataZoom[0].bottom = '28px'
        bondOption.yAxis[0].splitLine = {
            lineStyle: {
                type: 'dashed',
                color: "#ddd",
            }

        }
        
        if (data) {
            if (data.table) {
                this.refs.bondTable._initData(data.table, this.state.dimension, this.state.dimensionLatest)
            }
            data.figure['scenario_data'].forEach((item, index) => {
                areaMarket.push(Object.keys(item).toString())
            })

            areaMarket.forEach((item, index) => {
                let colorItem = ''

                if (data.figure['scenario_data'][index][item] === '1') {
                    colorItem = 'rgba(255, 201, 201, 0.4)'
                } else if (data.figure['scenario_data'][index][item] === '2') {
                    colorItem = 'rgba(255, 237, 183, 0.4)'
                } else if (data.figure['scenario_data'][index][item] === '3') {
                    colorItem = 'rgba(183, 227, 255, 0.4)'
                } else if (data.figure['scenario_data'][index][item] === '4') {
                    colorItem =  'rgba(188, 255, 183, 0.4)'
                }
                if (index === 0) {
                    markColor.push([{}, {
                        xAxis: areaMarket[index + 1].split('|')[0],
                        itemStyle: {color: colorItem}
                    }])
                } else if (index <= areaMarket.length - 2) {
                    markColor.push([{
                        xAxis: item.split('|')[0],
                        itemStyle: {color: colorItem}
                    }, {
                        xAxis: areaMarket[index + 1].split('|')[0],
                        itemStyle: {color: colorItem}
                    }])
                } else if (index === areaMarket.length -1) {
                    markColor.push([{
                        xAxis: item.split('|')[0],
                        itemStyle: {color: colorItem}
                    }, {}])
                }

            })

            bondOption.xAxis[0].data = data.figure.x_axis
            optionSeries = [{
                name: query.name,
                type: 'line',
                smooth: true,
                symbol: 'none',
                markArea: {
                    data: markColor
                },
                data: data.figure.fund_data
            }]
        }
        bondOption.series = optionSeries
        this.refs.bondMarket.setOpitions(bondOption)

    }

    // 期货市场表现标域图和表
    async _futureMarket () {
        const data = await this._getFuture()
        // console.log(data, 'future')
        const navType = {n_swanav: '复权累计净值', n_added_nav: '累计净值', n_nav: '单位净值'}
        let futureOption = JSON.parse(JSON.stringify(linesOptions))
        let optionSeries = []
        let areaMarket = []
        let markColor = []
        
        futureOption.legend.data = [query.name] 
        futureOption.grid.bottom = '16%'
        futureOption.grid.top = '46px'
        futureOption.dataZoom[0].bottom = '28px'
        futureOption.yAxis[0].name = navType[this.state.navType]
        futureOption.yAxis[0].axisTick = { show: false }
        futureOption.yAxis[0].splitLine = {
            lineStyle: {
                type: 'dashed',
                color: "#ddd",
            }

        }
        if (data) {
            if (data.table) {
                // this.refs.bondTable._initData(data.table, this.state.dimension, this.state.dimensionLatest)
                this.refs.futureTable._initData(data.table)
            }
            data.figure['scenario_data'].forEach((item, index) => {
                areaMarket.push(Object.keys(item).toString())
            })

            areaMarket.forEach((item, index) => {
                let colorItem = ''

                if (data.figure['scenario_data'][index][item] === 'high') {
                    colorItem = 'rgba(255, 201, 201, 0.4)'
                } else if (data.figure['scenario_data'][index][item] === 'mid') {
                    colorItem = 'rgba(255, 237, 183, 0.4)'
                } else if (data.figure['scenario_data'][index][item] === 'low') {
                    colorItem = 'rgba(183, 227, 255, 0.4)'
                    // colorItem =  'rgba(188, 255, 183, 0.4)'
                } else {
                    colorItem =  'rgba(188, 255, 183, 0.4)'
                }
                
                if (index === 0) {
                    markColor.push([{}, {
                        xAxis: item.split('|')[1],
                        itemStyle: {color: colorItem}
                    }])
                } else if (index <= areaMarket.length - 2) {
                    markColor.push([{
                        xAxis: item.split('|')[0],
                        itemStyle: {color: colorItem}
                    }, {
                        xAxis: item.split('|')[1],
                        itemStyle: {color: colorItem}
                    }])
                } else if (index === areaMarket.length -1) {
                    markColor.push([{
                        xAxis: item.split('|')[0],
                        itemStyle: {color: colorItem}
                    }, {}])
                }

            })


            futureOption.xAxis[0].data = data.figure.x_axis
            optionSeries = [{
                name: query.name,
                type: 'line',
                smooth: true,
                symbol: 'none',
                markArea: {
                    data: markColor
                },
                data: data.figure.fund_data
            }]
        }

        futureOption.series = optionSeries
        this.refs.futureMarket.setOpitions(futureOption)
    }

    // 设置 债券市场 阶段表现联动table返回
    displayRender (label) {
        return label[label.length - 1]
    }
    // 债券市场 阶段表现联动更改
    async dimessionChange (value) {
        const lastOptions = this.state.filterDimension.filter(item => {
            let swichValue = ''
            if (value[0] === '到期收益率') {
                swichValue = '到期收益率'
            } else if (value[0] === '宏观经济') {
                swichValue = '通货膨胀'
            } else if (value[0] === '通货膨胀') {
                swichValue = '宏观经济'
            } else if (value[0] === '货币供应') {
                swichValue = '实体融资需求'
            } else if (value[0] === '实体融资需求') {
                swichValue = '货币供应'
            }
            return item.value === swichValue
        })

        if (this.state.filterState) {
            await this.setState({lastDimensionOptions: lastOptions})
        }

        // console.log(lastOptions)
        const dimension = value[value.length - 1]
        const { dimensionLatest } = this.state
        if (dimension === dimensionLatest) {
            message.info('选择的指标不能同后面的指标一致')
            return 
        }
        await this.setState({dimension: dimension, lastDimensionOptions: lastOptions})
        // console.log(this.state.lastDimensionOptions[0].value, this.state.lastDimensionOptions[0].children[0].value)
        await this._bondMarket()
    }

    // 债券市场 阶段表现的设置
    async dimessionLatest (value) {
        const lastDimession = value[value.length -1]
        const { dimension } = this.state
        const dimenssionOptions = this.state.filterDimension.filter(item => {
            let swichValue = ''
            if (value[0] === '到期收益率') {
                swichValue = '到期收益率'
            } else if (value[0] === '宏观经济') {
                swichValue = '通货膨胀'
            } else if (value[0] === '通货膨胀') {
                swichValue = '宏观经济'
            } else if (value[0] === '货币供应') {
                swichValue = '实体融资需求'
            } else if (value[0] === '实体融资需求') {
                swichValue = '货币供应'
            }
            return item.value === swichValue
        })
        await this.setState({dimensionOptions: dimenssionOptions})
        if (!this.state.filterState) {
            await this.setState({dimensionOptions: dimenssionOptions})
        }

        if (lastDimession === dimension) {
            message.info('选择的指标不能同前面指标一致')
            return
        }

        await this.setState({dimensionLatest: lastDimession, filterState: false})
        await this._bondMarket()
    }

    // 市场阶段表现 切分维度选择
    async _neutralSelection (value) {
        value = value[value.length - 1]
        await this.setState({neutralType: value})
        let params = {
            token: cookie.get('token'),
            fundId: query.id,
            navType: this.state.navType,
            dateRange: this.state.neutralDate,
            // dimension: 'n_csi500_change'
            dimension: value
        }
        await this._neutralChart(params)
    }

    // 市场阶段表现 时间选择
    async _neutralStart (type, position, moment, str) {
        // console.log(type, position, moment, str)
        if (type && str) {
            if (position === 'start') {
                await this.setState({[type]: `${str}:${this.state.endDate}`, startDate: str})
            } else {
                await this.setState({[type]: `${this.state.startDate}:${str}`, endDate: str})
            }

            await this._neutralChart()
        }

    }

    // 市场分阶段表现——股票多头 选择指数
    async _socketSelection (value) {
        // console.log(value)
        await this.setState({indexName: value})
        await this._chartSocket()
    }

    // 股票多头选择置信区间
    async _socketLevel (value) {
        await this.setState({scoketLevel: value})
        await this._chartSocket()
    }

    // 净值类型选择
    async _navSelection (value) {
        // this.state.navType
        await this.setState({navType: value})
        await this._chartSocket()
        await this._neutralChart()
        await this._bondMarket()
        await this._futureMarket()
    }

    // 债券和期货置信水平选择
    async _changeLevel (type, value) {
        if (type && value) {
            await this.setState({[type]: value})
            if (type === 'bondLevel') {
                await this._bondMarket()
            } else if (type === 'futureLevel') {
                await this._futureMarket()  
            }
        } else {
            message.error('选择的置信水平或类型获取失败')
        }
    }

    //特殊场景净值走势图
    async _navChart () {
        let navOptions = JSON.parse(JSON.stringify(linesOptions))
        navOptions.tooltip.formatter = (value) => {
            let itemDesc = `${value[0].name}<br />`
            value.forEach(item => {
                itemDesc += `${item.marker}${item.seriesName}：${parseFloat(item.value).toFixed(2)}%<br />`
            })

            return itemDesc
        }

        this.refs.navCharts.setOpitions(navOptions)
    }

    //特殊场景回撤走势图
    async _downChart () {
        let downOptions = JSON.parse(JSON.stringify(areasOptions))
        downOptions.tooltip.formatter = (value) => {
            let itemDesc = `${value[0].name}<br />`
            value.forEach(item => {
                itemDesc += `${item.marker}${item.seriesName}：${parseFloat(item.value).toFixed(2)}%<br />`
            })

            return itemDesc
        }
        this.refs.downCharts.setOpitions(downOptions)
    }

    async componentDidMount () {
        await this._chartSocket()
        await this._marketVarChart()
        await this._neutralChart()
        await this._bondMarket()
        await this._futureMarket()

        await this._navChart()
        await this._downChart()
        // 监控，股票多头夏普比率输入
        let socketId = document.getElementById('socketId')
        if (socketId) {
            socketId.addEventListener('blur', async (e) => {
                const values = e.target.value
                if (values ==='' || values === undefined) {
                    await this.setState({socketSharpe: 'gz_10y'})
                    await this._chartSocket()
                    return
                }
                if (isNaN(values)) {
                    message.error('您输入的夏普比率不是一个数字')
                    return
                } else {
                    await this.setState({socketSharpe: values / 100})
                    await this._chartSocket()
                }
            }, false)
        }


        // 监控，债券夏普比率输入
        let bondsId = document.getElementById('bondsId')
        if (bondsId) {
            bondsId.addEventListener('blur', async (e) => {
                const values = e.target.value
                if (values ==='' || values === undefined) {
                    await this.setState({bondsSharpe: 'gz_10y'})
                    await this._bondMarket()
                    return
                }
                if (isNaN(values)) {
                    message.error('您输入的夏普比率不是一个数字')
                    return
                } else {
                    await this.setState({bondsSharpe: values / 100})
                    await this._bondMarket()
                }
            }, false)
        }
        
         // 监控，债券夏普比率输入
         let futureId = document.getElementById('futureId')
         if (futureId) {
            futureId.addEventListener('blur', async (e) => {
                const values = e.target.value
                if (values ==='' || values === undefined) {
                    await this.setState({futureSharpe: 'gz_10y'})
                    await this._futureMarket()
                    return
                }
                if (isNaN(values)) {
                    message.error('您输入的夏普比率不是一个数字')
                    return
                } else {
                    await this.setState({futureSharpe: values / 100})
                    await this._futureMarket()
                }
            }, false)
         }
    }

    async _checkDateRender (type, position, moment, str) {

        if (type && str && position) {
            if (position === 'start') {
                await this.setState({[type]: `${str}:${this.state.endDate}`, startDate: str})
            } else {
                await this.setState({[type]: `${this.state.startDate}:${str}`, endDate: str})
            }

            if (type === 'socketDate') {
                await this._chartSocket()
            } else if (type === 'bondDate') {
                await this._bondMarket()
            } else if (type === 'futrueDate') {
                await this._futureMarket()
            }
        }
    }

    async _radarDate (type, position, moment, str) {
        console.log(type, position, moment, str)
        if (type && str && position) {
            if (position === 'start') {
                await this.setState({[type]: `${str}:${this.state.endDate}`, randarStart: str})
            } else {
                await this.setState({[type]: `${this.state.startDate}:${str}`, randarEnd: str})
            }

            await this._marketVarChart()
        }
    }

    // 期货选择指数类型
    async _futureDev (value) {
        const futureDev = value[value.length - 1]
        if (futureDev) {
            await this.setState({futureDev})
        }
        await this._futureMarket()
    }

    // 期货M日波动率设置
    async _futureScenario (value) {
        if (value) {
            await this.setState({futureDay: value})
        }
        await this._futureMarket()
    }

    // 期货选择时间
    async _futureDate (type, position, moment, str) {
        if (type && position && str) {
            if (position === 'start') {
                await this.setState({futureDate: `${str}:${this.state.futureEnd}`, futureStart: str})
            } else {
                await this.setState({futureDate: `${this.state.futureStart}:${str}`, futureEnd: str})    
            }
            await this._futureMarket()
        }
    }

    async _quantileChange (value) {
        const values = value.target.value

        if (values) {
            if (isNaN(values)) {
                message.error('N分位只能输入数字，请重新输入')
                return
            }

            if (values > 50 || values < 0) {
                message.error('N分位只能小于50，大于0的整数')
                return
            }

            if (values.indexOf('.') !== -1) {
                message.error('N分位不能输入小数，只能输入整数')
                return
            }

            await this.setState({nQuantile: values})
            await this._futureMarket()
        } else {
            await this.setState({nQuantile: '0.2'})
            await this._futureMarket()
        }
    }

    render () {
        return (
        <div className={`${SceneStyle.scene_container_wrapper}`}>
            <div className={`${SceneStyle.position_absolute} ${SceneStyle.scene_export_nav}`}>
                <span>净值类型：</span>
                <Select style={{width: '140px'}} placeholder='复权累计净值' onChange={this._navSelection.bind(this)} className={`${SceneStyle.selection_wrapper}`}>
                    <Option value='n_swanav'>复权累计净值</Option>
                    <Option value='n_nav'>单位净值</Option>
                    <Option value='n_added_nav'>累计净值</Option>
                </Select>
                <Button type={'danger'}>导出</Button>
            </div>
            <div className={ProductStyle.holder_wrapper}>
                <div className={ProductStyle.holder_btn_dec_large}><span className={'iconfont iconqushitu'}></span>市场分阶段表现——股票多头</div>
                <WrapperHeader title='市场分阶段表现' fn={this.exportPDF} iconStatus={true}>
                    <div className='float_right product_select_date'>
                        <span>指数：</span>
                        <Select style={{width: '140px'}} placeholder='沪深300指数' onChange={this._socketSelection.bind(this)} className={`${SceneStyle.selection_wrapper}`}>
                            <Option value='c_hs300_trend'>沪深300指数</Option>
                            <Option value='c_csi500_trend'>中证500指数</Option>
                            <Option value='c_csi800_trend'>中证800指数</Option>
                            <Option value='c_sse_trend'>上证指数</Option>
                            <Option value='c_gem_trend'>创业板指数</Option>
                        </Select>
                        <DatePicker locale={locale} allowClear={false} onChange={this._checkDateRender.bind(this,'socketDate', 'start')} placeholder={'开始日期'} />
                        <strong>~</strong>
                        <DatePicker locale={locale} allowClear={false} onChange={this._checkDateRender.bind(this,'socketDate', 'end')} placeholder={'结束日期'} />
                    </div>
                </WrapperHeader>

                <CommonCharts idName={`socketMarket`} ref={`socketMarket`} styles={{width: '100%', height: '550px'}} />
                <div className={`${SceneStyle.area_desc_tips}`} style={ {visibility: this.state.socketDesc ? 'visible' : 'hidden'} }>
                    <div className={`${SceneStyle.area_desc_up} ${SceneStyle.area_desc_block}`}>
                        <span>市场上涨</span>
                    </div>
                    <div className={`${SceneStyle.area_desc_normal} ${SceneStyle.area_desc_block}`}>
                        <span>市场震荡</span>
                    </div>
                    <div className={`${SceneStyle.area_desc_down_yellow} ${SceneStyle.area_desc_block}`}>
                        <span>市场下跌</span>
                    </div>
                </div>

                <div className={`mt_10 clear-fix`}>
                    <div className={`clear-fix pb_10`}>
                        <div className={`float_right`}>
                            <span>置信水平：</span>
                            <Select style={{width: '140px'}} placeholder='90%' onChange={this._socketLevel.bind(this)} className={`${SceneStyle.selection_wrapper}`}>
                                <Option value="0.90">90%</Option>
                                <Option value="0.95">95%</Option>
                                <Option value="0.99">99%</Option>
                            </Select>
                        </div>
                    </div>

                    <SceneTable ref='socketTable' />
                </div>
            </div>

            {/* 市场中性 */}
            <div className={`${ProductStyle.holder_wrapper} mt_20`}>
                <div className={ProductStyle.holder_btn_dec_large}><span className={'iconfont iconshichang'}></span>市场分阶段表现——市场中性</div>
                <WrapperHeader title='影响净值的关键市场变量' fn={this.exportPDF} iconStatus={true}>
                    <div className='float_right product_select_date'>
                        <DatePicker locale={locale} allowClear={false} onChange={this._radarDate.bind(this, 'randarDate', 'start')} placeholder={'开始日期'} />
                        <strong>~</strong>
                        <DatePicker locale={locale} allowClear={false} onChange={this._radarDate.bind(this, 'randarDate', 'end')} placeholder={'结束日期'} />
                    </div>
                </WrapperHeader>

                <CommonCharts idName={`socketMarketVar`} ref={`socketMarketVar`} styles={{width: '100%', height: '600px'}} />

                <div className={`mt_20`}>
                    <WrapperHeader title='市场分阶段表现' fn={this.exportPDF} iconStatus={true}>
                        <div className='float_right product_select_date'>
                            <DatePicker locale={locale} allowClear={false} onChange={this._neutralStart.bind(this, 'neutralDate', 'start')} placeholder={'开始日期'} />
                            <strong>~</strong>
                            <DatePicker locale={locale} allowClear={false} onChange={this._neutralStart.bind(this, 'neutralDate', 'end')} placeholder={'结束日期'} />
                        </div>
                    </WrapperHeader>
                </div>
                <div className={`clear-fix`}>
                    <div className={`float_left ${SceneStyle.left_container}`}>
                        <div className={`${SceneStyle.selection_neutral} clear-fix mt_20`}>
                            <div className={`float_right`} id={`cascader_container_neutral`}>
                                <span>切分维度：</span>
                                <Cascader allowClear={false} options={neutralOptions} onChange={this._neutralSelection.bind(this)} expandTrigger="hover" placeholder={`年化基差成本`} className={`select_cascader_wrapper`} displayRender={this.displayRender.bind(this)} getPopupContainer={() => document.getElementById('cascader_container_neutral')} />
                            </div>
                        </div>
                       <CommonCharts idName={`neutralChart`} ref={`neutralChart`} styles={{width: '100%', height: '550px'}} />
                    </div>
                    <div className={`float_right ${SceneStyle.right_container}`}>
                        <div className={`mt_20`}>
                            <SceneBasis ref={`neutralTable`} />
                        </div>
                    </div>
                </div>
            </div>


            <div className={`${ProductStyle.holder_wrapper} mt_20`}>
                <div className={ProductStyle.holder_btn_dec_large}><span className={'iconfont iconzhaiquan'}></span>市场分阶段表现——债券</div>
                <WrapperHeader title='市场分阶段表现' fn={this.exportPDF} iconStatus={true}>
                    <div className='float_right product_select_date'>
                        <div id={`cascader_container_scene`} style={{float: 'left', marginRight: '10px'}}>
                            <Cascader allowClear={false} options={this.state.dimensionOptions} onChange={this.dimessionChange.bind(this)} expandTrigger="hover" placeholder={`长债收益率`} className={`select_cascader_wrapper`} displayRender={this.displayRender.bind(this)} getPopupContainer={() => document.getElementById('cascader_container_scene')} />
                        </div>

                        <div id={`cascader_container_option`} style={{float: 'left'}}>
                            <Cascader allowClear={false} style={{width: '140px'}} options={this.state.lastDimensionOptions} onChange={this.dimessionLatest.bind(this)} expandTrigger="hover" placeholder={`期限利差`} className={`select_cascader_wrapper`} displayRender={this.displayRender.bind(this)} getPopupContainer={() => document.getElementById('cascader_container_option')} />
                        </div>

                        <span className={`ml_20`}>统计日期：</span>
                        <DatePicker locale={locale} allowClear={false} onChange={this._checkDateRender.bind(this,'bondDate', 'start')} placeholder={'开始日期'} />
                        <strong>~</strong>
                        <DatePicker locale={locale} allowClear={false} onChange={this._checkDateRender.bind(this,'bondDate', 'end')} placeholder={'结束日期'} />
                    </div>
                </WrapperHeader>

                <CommonCharts idName={`bondMarket`} ref={`bondMarket`} styles={{width: '100%', height: '550px'}} />
                <div className={`${SceneStyle.area_desc_tips}`} style={{visibility: this.state.bondDesc ? 'visible' : 'hidden'}}>
                    <div className={`${SceneStyle.area_desc_up} ${SceneStyle.area_desc_block}`}>
                        <span>{`${dimensionDesc[0][this.state.dimension].name}${dimensionDesc[0][this.state.dimension].status} & ${dimensionDesc[0][this.state.dimensionLatest].name}${dimensionDesc[0][this.state.dimensionLatest].status}`}</span>
                    </div>
                    <div className={`${SceneStyle.area_desc_normal} ${SceneStyle.area_desc_block}`}>
                        <span>{`${dimensionDesc[0][this.state.dimension].name}${dimensionDesc[0][this.state.dimension].status} & ${dimensionDesc[1][this.state.dimensionLatest].name}${dimensionDesc[1][this.state.dimensionLatest].status}`}</span>
                    </div>
                    <div className={`${SceneStyle.area_desc_down_yellow} ${SceneStyle.area_desc_block}`}>
                        <span>{`${dimensionDesc[1][this.state.dimension].name}${dimensionDesc[1][this.state.dimension].status} & ${dimensionDesc[0][this.state.dimensionLatest].name}${dimensionDesc[0][this.state.dimensionLatest].status}`}</span>
                    </div>
                    <div className={`${SceneStyle.area_desc_down_green} ${SceneStyle.area_desc_block}`}>
                        <span>{`${dimensionDesc[1][this.state.dimension].name}${dimensionDesc[1][this.state.dimension].status} & ${dimensionDesc[1][this.state.dimensionLatest].name}${dimensionDesc[1][this.state.dimensionLatest].status}`}</span>
                    </div>
                </div>
                <div className={`mt_20 clear-fix`}>
                    <div className={`clear-fix pb_10`}>
                        <div className={`float_right`}>
                            <span>置信水平：</span>
                            <Select style={{width: '140px'}} placeholder='90%' onChange={this._changeLevel.bind(this, 'bondLevel')} className={`${SceneStyle.selection_wrapper}`}>
                                <Option value="0.90">90%</Option>
                                <Option value="0.95">95%</Option>
                                <Option value="0.99">99%</Option>
                            </Select>
                        </div>
                    </div>

                    <SceneTableBond ref='bondTable' />
                </div>
            </div>


            <div className={`${ProductStyle.holder_wrapper} mt_20`}>
                <div className={ProductStyle.holder_btn_dec_large}><span className={'iconfont iconqihuo'}></span>市场分阶段表现——期货</div>
                <WrapperHeader title='市场份额阶段' fn={this.exportPDF} iconStatus={true}>
                    <div className='float_right product_select_date'>
                        <div id={`cascader_container_future`} style={{display: 'inline-block', marginRight: '10px'}}>
                            <Cascader options={futureOptions} onChange={this._futureDev.bind(this)} expandTrigger="hover" placeholder={`南华商品指数`} className={`select_cascader_wrapper`} displayRender={this.displayRender.bind(this)} getPopupContainer={() => document.getElementById('cascader_container_future')} />
                        </div>
                        
                        <Tooltip placement="bottom" title={`N分位取值0到50之间的整数`}><Input className={`${SceneStyle.n_quantile}`} placeholder={`N分位`} onBlur={this._quantileChange.bind(this)} /></Tooltip>
                        <span className={`ml_20`}>M日波动率：</span>
                        <Select style={{width: '140px'}} placeholder='30天' onChange={this._futureScenario.bind(this)}>
                            <Option value='scenario_future_30'>30天</Option>
                            <Option value='scenario_future_60'>60天</Option>
                            <Option value='scenario_future_90'>90天</Option>
                            <Option value='scenario_future_180'>180天</Option>
                            <Option value='scenario_future_360'>360天</Option>
                        </Select>
            
                        <span className={`ml_20`}>统计日期：</span>
                        <DatePicker allowClear={false} locale={locale} onChange={this._futureDate.bind(this, 'futureDate', 'start')} placeholder={'开始日期'} />
                        <strong>~</strong>
                        <DatePicker allowClear={false} locale={locale} onChange={this._futureDate.bind(this, 'futureDate', 'end')} placeholder={'结束日期'} />
                    </div>
                </WrapperHeader>

                <CommonCharts idName={`futureMarket`} ref={`futureMarket`} styles={{width: '100%', height: '550px'}} />
                <div className={`${SceneStyle.area_desc_tips}`} style={{visibility: this.state.futureDesc ? 'visible' : 'hidden'}}>
                    <div className={`${SceneStyle.area_desc_up} ${SceneStyle.area_desc_block}`}>
                        <span>高波动</span>
                    </div>
                    <div className={`${SceneStyle.area_desc_normal} ${SceneStyle.area_desc_block}`}>
                        <span>震荡</span>
                    </div>
                    <div className={`${SceneStyle.area_desc_down_yellow} ${SceneStyle.area_desc_block}`}>
                        <span>低波动</span>
                    </div>
                </div>
                <div className={`mt_20 clear-fix`}>
                    <div className={`clear-fix pb_10`}>
                        <div className={`float_right`}>
                            <span>置信水平：</span>
                            <Select style={{width: '140px'}} onChange={this._changeLevel.bind(this, 'futureLevel')} placeholder='90%' className={`${SceneStyle.selection_wrapper}`}>
                                <Option value="0.90">90%</Option>
                                <Option value="0.95">95%</Option>
                                <Option value="0.99">99%</Option>
                            </Select>
                        </div>
                    </div>

                    <SceneTableFuture ref={`futureTable`} />
                </div>
            </div>


            <div className={`${ProductStyle.holder_wrapper} mt_20`}>
                <div className={ProductStyle.holder_btn_dec_large}><span className={'iconfont iconjuecebiao'}></span>特殊场景分析</div>
                <div className={`${SceneStyle.customer_border_wrapper} mb_10`}>
                    <SceneHeaders />
                </div>
                <WrapperHeader title='单位净值走势' fn={this.exportPDF} iconStatus={true}></WrapperHeader>
                <CommonCharts idName={`navCharts`} ref={`navCharts`} styles={{width: '100%', height: '600px'}} />
                <div className={`mt_20`}>
                    <WrapperHeader title='回撤走势图' fn={this.exportPDF} iconStatus={true}></WrapperHeader>
                </div>
                <CommonCharts idName={`downCharts`} ref={`downCharts`} styles={{width: '100%', height: '600px'}} />

                <div className={`mt_20`}>
                    <WrapperHeader title='收益风险指标' fn={this.exportPDF} iconStatus={true}></WrapperHeader>
                    <div className={`mt_10`}>
                        <RiskTable  productName={this.state.productName} _initRateRisk={this._getRiskRate.bind(this)} />
                    </div>
                </div>
            </div>

        </div>)
    }
}
